package com.dwxt.parabolic.service;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.Page;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.base.YesOrNo;
import com.dwxt.common.util.IDUtils;
import com.dwxt.common.util.MD5Utils;
import com.dwxt.parabolic.base.QuantityType;
import com.dwxt.parabolic.base.RoleType;
import com.dwxt.parabolic.dao.AreaMapper;
import com.dwxt.parabolic.dao.InstallCompanyMapper;
import com.dwxt.parabolic.dao.UserMapper;
import com.dwxt.parabolic.entity.*;
import com.dwxt.parabolic.utils.RedisUtil;
import com.dwxt.parabolic.utils.RequestUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.bytebuddy.matcher.IsNamedMatcher;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class InstallCompanyService {
    @Autowired
    private InstallCompanyMapper installCompanyMapper;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private UserService userService;
    @Autowired
    private DeviceService deviceService;

    public BaseResult getCompanyList(Page page, InstallCompany installCompany) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        InstallCompanyExample example = new InstallCompanyExample();
        example.setOrderByClause("create_time desc");
        InstallCompanyExample.Criteria criteria = example.createCriteria();
        if (!RequestUtil.getCurrentCompanyId().equals("0")) {
            criteria.andIdEqualTo(RequestUtil.getCurrentCompanyId());
        }
        if (StringUtils.isNotBlank(installCompany.getName())) {
            criteria.andNameLike("%" + installCompany.getName() + "%");
        }
        if (StringUtils.isNotBlank(installCompany.getUserName())) {
            criteria.andUserNameLike("%" + installCompany.getUserName() + "%");
        }
        List<InstallCompany> installCompanyList = installCompanyMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo(installCompanyList);
        List<InstallCompany> collect = installCompanyList.stream().map(company -> {
            User user = userService.selectByPrimaryKey(company.getUserId());
            company.setUserName(user.getUserName());
            company.setPhoneNumber(user.getPhoneNumber());
            return company;
        }).collect(Collectors.toList());
        pageInfo.setList(collect);
        return BaseResult.ok(pageInfo);
    }

    @Transactional
    public BaseResult add(InstallCompany company, String code) {
        /*String redisCode = RedisUtil.get(company.getPhoneNumber(), String.class);
        if (!code.equalsIgnoreCase(redisCode)) {
            return BaseResult.build(StatusCode.SMS_CODE_ERROR);
        }*/
        User user = userService.selectByPhone(company.getPhoneNumber());
        if (user != null) {
            return BaseResult.build(StatusCode.PHONE_EXIST);
        }

        company.setId(IDUtils.genItemId());
        //插入用户信息（负责人信息）
        user = User.builder().id(IDUtils.genItemId()).companyId(company.getId()).isManager(YesOrNo.YES)
                .password(MD5Utils.MD5Encode("123456")).phoneNumber(company.getPhoneNumber())
                .roleId("2").userName(company.getUserName()).build();
        userService.insertSelective(user);

        //插入公司数据
        Area area = areaMapper.selectByPrimaryKey(company.getAreaId());
        Area city = areaMapper.selectByPrimaryKey(company.getCityId());
        Area province = areaMapper.selectByPrimaryKey(company.getProvinceId());

        company.setAreaName(area.getName());
        company.setCityName(city.getName());
        company.setProvinceName(province.getName());
        company.setUserId(user.getId());
        installCompanyMapper.insertSelective(company);


        return BaseResult.ok();
    }

    public BaseResult update(InstallCompany company) {
        installCompanyMapper.updateByPrimaryKeySelective(company);
        return BaseResult.ok();
    }

    @Transactional
    public BaseResult delete(String id) {
        installCompanyMapper.deleteByPrimaryKey(id);
        userService.deleteByCompanyId(id);
        return BaseResult.ok();
    }

    public void addByQuantityType(String companyId, QuantityType type, int count) {
        InstallCompany installCompany = installCompanyMapper.selectByPrimaryKey(companyId);
        if (type.equals(QuantityType.user)) {
            installCompany.setUserCount(installCompany.getUserCount() + count);
        }
        if (type.equals(QuantityType.company)) {
            installCompany.setCompanyCount(installCompany.getCompanyCount() + count);
        }
        installCompanyMapper.updateByPrimaryKeySelective(installCompany);
    }

    public InstallCompany selectByPrimaryKey(String installCompanyId) {
        return installCompanyMapper.selectByPrimaryKey(installCompanyId);
    }

    public List<InstallCompany> selectById(String installCompanyId) {
        if ("0".equals(installCompanyId)) {
            InstallCompanyExample example = new InstallCompanyExample();
            return installCompanyMapper.selectByExample(example);
        }
        return Arrays.asList(installCompanyMapper.selectByPrimaryKey(installCompanyId));
    }

    public BaseResult currentCompany() {
        String userType = RequestUtil.getCurrentUserType();
        if (RoleType.SUPER_ADMIN.getType().equals(userType)) {
            return BaseResult.ok();
        }
        if (RoleType.INSTALL_COMPANY.getType().equals(userType)) {
            InstallCompany installCompany = installCompanyMapper.selectByPrimaryKey(RequestUtil.getCurrentCompanyId());
            return BaseResult.ok(installCompany);
        }
        if (RoleType.COMPANY.getType().equals(userType)) {
            Company company = companyService.selectByPrimaryKey(RequestUtil.getCurrentCompanyId());
            InstallCompany installCompany = installCompanyMapper.selectByPrimaryKey(company.getInstallCompanyId());
            return BaseResult.ok(installCompany);
        }

        return BaseResult.build(StatusCode.PARAMETER_WRONG);
    }

    @Transactional
    public BaseResult startOrEnd(String id) {
        InstallCompany installCompany = installCompanyMapper.selectByPrimaryKey(id);

        if (installCompany.getStatus() == YesOrNo.YES) {
            userService.endByInstallCompanyId(id);
            deviceService.endAllByInstallId(id);
            installCompany.setStatus(YesOrNo.NO);
            installCompanyMapper.updateByPrimaryKeySelective(installCompany);
        } else {
            userService.startByInstallCompanyId(id);
            installCompany.setStatus(YesOrNo.YES);
            installCompanyMapper.updateByPrimaryKeySelective(installCompany);
        }
        return BaseResult.ok();
    }
}


